
package com.heimali.happyreader.core.manager;

import com.heimali.happyreader.HappyReaderApplication;
import com.heimali.happyreader.config.ActionCode;
import com.heimali.happyreader.config.ErrorCode;
import com.heimali.happyreader.core.bean.ActionPublisherWithThreadPoolBase;
import com.heimali.happyreader.core.bean.ManagedRuntimeException;
import com.heimali.happyreader.core.bean.PoolThreadFactory;
import com.heimali.happyreader.core.bean.User;
import com.heimali.happyreader.core.intf.ITaskListenerSimple;
import com.heimali.happyreader.core.net.UserApi;
import com.heimali.happyreader.utils.Utils;

import java.util.Date;
import java.util.concurrent.Executors;

public class UserManager extends ActionPublisherWithThreadPoolBase {
    public static String TAG = "UserManager";

    private String mPoolNameHighPriority;
    
    private UserApi mApi;

    public UserManager() {
        mApi = new UserApi();
        mPoolNameHighPriority = "pool-worker-high-priority-user-" + Utils.DATE_FORMAT_3.format(new Date());
        mThreadPool.initPool(mPoolNameHighPriority, Executors.newCachedThreadPool(new PoolThreadFactory(mPoolNameHighPriority)));
    }

    @Override
    protected void asyncDoNamedJob(String jobName, Object... args) {
        if ("login".equals(jobName)) {
            doLogin((String) args[0], (String) args[1]);
        } else if ("logout".equals(jobName)) {
            doLogout((ITaskListenerSimple) args[0], (String) args[1]);
        }
    }

    public void asyncLogin(String username, String password) {
        mThreadPool.submit(mPoolNameHighPriority, new NamedAsyncJob("login", username, password));
    }

    private void doLogin(String username, String password) {
        try{
            User user = mApi.login(username, password);
            user.save();
            HappyReaderApplication.loginUserInfo = user;
            publishAction(ActionCode.LOGIN_SUCCESS, user);
        }catch(Exception e) {
            publishException(e);
        }
    }

    public void asyncLogout(ITaskListenerSimple taskListener, String uid) {
        mThreadPool.submit(mPoolNameHighPriority, new NamedAsyncJob("logout", taskListener, uid));
    }

    private void doLogout(ITaskListenerSimple taskListener, String uid) {

    }
    
    /**
     * 处理错误
     * @param e
     */
    private void publishException(Exception e) {
        if (e instanceof ManagedRuntimeException) {
            publishAction(((ManagedRuntimeException) e).errorCode, e);
        }else {
            publishAction(ActionCode.LOGIN_FAILED, new ManagedRuntimeException(ErrorCode.UNKNOWN_ERROR, "unknown error"));
        }
    }
}
